//
//  HomeV2.m
//  樓盤王
//
//  Created by Jacky Mok on 6/12/2017.
//  Copyright © 2017 OR Media Limited. All rights reserved.
//

#import "HomeV2.h"
#import "AppDelegate.h"
#import "HomeV2HeaderCell.h"
#import "HomeV2ToolCell.h"
#import "TableTwoByTwoV2.h"
#import "UIImageEffects.h"

#define TOOL_CELL_HEIGHT 200
@interface HomeV2 ()

@end

@implementation HomeV2
-(id) initWithStyle:(UITableViewStyle)style {
    if (self = [super initWithStyle:style]) {
        
        delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
        TOP_CELL_HEIGHT = (100.0/320)*delegate.screenWidth;
        [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        headerCell = [[HomeV2HeaderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HomeHeader" withCellHeight:TOP_CELL_HEIGHT*2 andType:@"hometop"];
        
        toolCell = [[HomeV2ToolCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ToolHeader" withCellHeight:TOOL_CELL_HEIGHT];
        middleCell = [[HomeV2HeaderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HomeHeader" withCellHeight:TOP_CELL_HEIGHT andType:@"homebottom"];
        [middleCell hideSearchBar:YES];
      
        loadingMore = NO;
        self.tableView.delegate = self;
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/app/app-get-sites",delegate.domain]];
        NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
            
            if (error) {
                //NSLog(@"Error,%@", [error localizedDescription]);
            } else {
                NSDictionary *jsondata = [NSJSONSerialization
                                     JSONObjectWithData:data
                                     options:kNilOptions
                                     error:&error];
                if (!error) {
                    tabledata = [[jsondata objectForKey:@"data"] mutableCopy];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.tableView reloadData];
                    });
                }
            }
        }];
        
        
        url = [NSURL URLWithString:[NSString stringWithFormat:@"%@app/home_v2",delegate.domain]];
        urlRequest = [NSURLRequest requestWithURL:url];
        queue = [[NSOperationQueue alloc] init];
        
        [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
            if (error) {
                NSLog(@"Home Network Error,%@", [error localizedDescription]);
            }
            else {
                NSDictionary *jdata = [NSJSONSerialization
                                       JSONObjectWithData:data
                                       options:kNilOptions
                                       error:&error];
                if (!error) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        jsondata = [jdata objectForKey:@"data"];
                        int idx;
                        int topcount = 0;
                        int botcount = 0;
                        NSMutableArray *toparr = [[NSMutableArray alloc] init];
                        NSMutableArray *botarr = [[NSMutableArray alloc] init];
                        for (idx =0; idx < [jsondata count]; idx++) {
                            UIImageView *i = [[UIImageView alloc] initWithFrame:CGRectMake(topcount*delegate.screenWidth,0,delegate.screenWidth,TOP_CELL_HEIGHT)];
                            NSString *url = [[jsondata objectAtIndex:idx] objectForKey:@"img"];
                            if ([[[jsondata objectAtIndex:idx] objectForKey:@"subtype"] isEqualToString:@"homefull"]) {
                                // shoot this image over to ViewController.
                                [[NSNotificationCenter defaultCenter] postNotificationName:FULL_ADD_LOAD object:url];
                            } else {
                                [i setImage:[delegate getImage:url andTag:0  callback:^(UIImage *image, int tag) {
                                    [i setImage:[UIImageEffects imageByApplyingLightEffectToImage:image]];
                                    [i setContentMode:UIViewContentModeScaleAspectFill];
                                    [i setTag:idx];
                                    UIImageView *fe = [[UIImageView alloc] initWithImage:image];
                                    
                                    if ([[[jsondata objectAtIndex:idx] objectForKey:@"subtype"] isEqualToString:@"hometop"]) {
                                        [fe setFrame:CGRectMake(0,0,delegate.screenWidth,TOP_CELL_HEIGHT*2)];
                                    } else {
                                        [fe setFrame:CGRectMake(0,0,delegate.screenWidth,TOP_CELL_HEIGHT)];
                                    }
                                    [fe setContentMode:UIViewContentModeScaleAspectFit];
                                    [i addSubview:fe];
                                    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(adtapped:)];
                                    i.tag = idx;
                                    [i addGestureRecognizer:tap];
                                }]];
                            
                                [i setUserInteractionEnabled:YES];
                                
                                if ([[[jsondata objectAtIndex:idx] objectForKey:@"subtype"] isEqualToString:@"hometop"]) {
                                    [toparr addObject:i];
                                    [i setFrame:CGRectMake(topcount*delegate.screenWidth,0,delegate.screenWidth,TOP_CELL_HEIGHT*2)];
                                    topcount++;
                                } else if ([[[jsondata objectAtIndex:idx] objectForKey:@"subtype"] isEqualToString:@"homebottom"]) {
                                    [botarr addObject:i];
                                    [i setFrame:CGRectMake(botcount*delegate.screenWidth,0,delegate.screenWidth,TOP_CELL_HEIGHT)];
                                    botcount++;
                                }
                                
                            }
                            [headerCell addToScroll:toparr];
                            [middleCell addToScroll:botarr];
                        }
                    });
                }
            }
        }];
        
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0)
        return 3;
    else
        return ceil([tabledata count]/2);
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            return headerCell;
        } else if (indexPath.row==1) {
            return toolCell;
        } else if (indexPath.row==2) {
            return middleCell;
        } else {
            return [tableView dequeueReusableCellWithIdentifier:@"home" forIndexPath:indexPath];
        }
    } else if (indexPath.section==1){
        TableTwoByTwoV2 *cell = (TableTwoByTwoV2*)[tableView dequeueReusableCellWithIdentifier:@"homev2table"];
        
        if (!cell) {
            cell = [[TableTwoByTwoV2 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"homev2table"];
        }
        cell.data1 = [tabledata objectAtIndex:indexPath.row*2];
        if ([tabledata count]>=indexPath.row*2+1) {
            // enter two
            cell.data2 = [tabledata objectAtIndex:indexPath.row*2+1];
        } else {
            // enter 1
            cell.data2 = nil;
        }
        // Configure the cell...
        [cell redraw];
        
        return cell;
    }
    return [tableView dequeueReusableCellWithIdentifier:@"EMPTY"];
}
-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section==0)
        return delegate.headerHeight-delegate.XPAD;
    else
        return 0;
}
-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectMake(0,0,delegate.screenWidth,delegate.headerHeight)];
    
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            return TOP_CELL_HEIGHT*2;
        } else if (indexPath.row==1) {
            return TOOL_CELL_HEIGHT;
        } else if (indexPath.row==2) {
            return TOP_CELL_HEIGHT;
        }
    } else if (indexPath.section==1) {
        return HOMEPAGETABLEROW_HEIGHT+10;
    }
    return UITableViewAutomaticDimension;
}
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
    
    CGPoint offset = aScrollView.contentOffset;
    CGRect bounds = aScrollView.bounds;
    CGSize size = aScrollView.contentSize;
    UIEdgeInsets inset = aScrollView.contentInset;
    float y = offset.y + bounds.size.height - inset.bottom;
    float h = size.height;
    float reload_distance = 100;
    /*
     if(h > 0 && y > h + reload_distance) {
     //scroll down
     [[NSNotificationCenter defaultCenter]postNotificationName:SCROLL_DOWN object:nil];
     } else {
     [[NSNotificationCenter defaultCenter]postNotificationName:SCROLL_UP object:nil];
     }
     */
    if ([tabledata count]>=10 && !loadingMore) {
        loadingMore = YES;
        if(h > 0 && y > h + reload_distance) {
            [delegate startLoading];
            int datacount = (int)[tabledata count];
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/app/app-get-sites?ap=%d",delegate.domain,datacount]];
            NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
            NSOperationQueue *queue = [[NSOperationQueue alloc] init];
            [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                if (error) {
                    //NSLog(@"Error,%@", [error localizedDescription]);
                    [delegate stopLoading];
                    loadingMore = NO;
                } else {
                    [delegate stopLoading];
                    loadingMore = NO;
                    NSDictionary *jsondata = [NSJSONSerialization
                                              JSONObjectWithData:data
                                              options:kNilOptions
                                              error:&error];
                    if (!error) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [tabledata addObjectsFromArray:[jsondata objectForKey:@"data"]];
                            [self.tableView reloadData];
                            int row = ceil(datacount/2);
                            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:1];
                            [self.tableView scrollToRowAtIndexPath:indexPath
                                                 atScrollPosition:UITableViewScrollPositionTop
                                                         animated:YES];
                        });
                    }
                }
            }];
            
            
        } else {
            loadingMore = NO;
        }
    }
}
-(void) adtapped:(UITapGestureRecognizer *)t {
    if (![[[jsondata objectAtIndex:t.view.tag] objectForKey:@"url"] isEqualToString:@""]) {
        NSURL *url = [NSURL URLWithString:[[[jsondata objectAtIndex:t.view.tag] objectForKey:@"url"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        if ([[UIApplication sharedApplication] canOpenURL: url]) {
            [[UIApplication sharedApplication] openURL: url];
        }
    }
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
